# -*- coding: utf-8 -*-
"""
配置验证工具
用于检查配置的完整性和正确性
"""

import os
import re
from typing import Dict, List, Tuple


class ConfigValidator:
    """配置验证器"""
    
    def __init__(self, config_dict: Dict):
        self.config = config_dict
        self.errors = []
        self.warnings = []
    
    def validate_all(self) -> Tuple[bool, List[str], List[str]]:
        """验证所有配置"""
        self.errors = []
        self.warnings = []
        
        # 验证基础配置
        self._validate_basic_config()
        
        # 验证数据库配置
        self._validate_database_config()
        
        # 验证安全配置
        self._validate_security_config()
        
        # 验证微信配置
        self._validate_wechat_config()
        
        # 验证文件上传配置
        self._validate_upload_config()
        
        # 验证日志配置
        self._validate_logging_config()
        
        return len(self.errors) == 0, self.errors, self.warnings
    
    def _validate_basic_config(self):
        """验证基础配置"""
        required_keys = ['SECRET_KEY', 'FLASK_ENV']
        
        for key in required_keys:
            if not self.config.get(key):
                self.errors.append(f"缺少必需的配置项: {key}")
        
        # 检查SECRET_KEY强度
        secret_key = self.config.get('SECRET_KEY', '')
        if secret_key and len(secret_key) < 32:
            self.warnings.append("SECRET_KEY长度不足32位，建议使用更强的密钥")
        
        if 'dev-secret' in secret_key or 'change-in-production' in secret_key:
            self.warnings.append("检测到默认SECRET_KEY，生产环境请更换")
    
    def _validate_database_config(self):
        """验证数据库配置"""
        db_keys = ['MYSQL_HOST', 'MYSQL_PORT', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE']
        
        for key in db_keys:
            if not self.config.get(key):
                self.errors.append(f"缺少数据库配置项: {key}")
        
        # 检查数据库连接池配置
        pool_size = self.config.get('DB_POOL_SIZE', 10)
        if pool_size > 50:
            self.warnings.append("数据库连接池大小过大，可能影响性能")
        
        if pool_size < 5:
            self.warnings.append("数据库连接池大小过小，可能影响并发性能")
    
    def _validate_security_config(self):
        """验证安全配置"""
        jwt_key = self.config.get('JWT_SECRET_KEY', '')
        if not jwt_key:
            self.errors.append("缺少JWT_SECRET_KEY配置")
        elif len(jwt_key) < 32:
            self.warnings.append("JWT_SECRET_KEY长度不足32位，建议使用更强的密钥")
        
        # 检查CORS配置
        cors_origins = self.config.get('CORS_ORIGINS', [])
        if isinstance(cors_origins, str):
            cors_origins = cors_origins.split(',')
        
        if not cors_origins or '*' in cors_origins:
            self.warnings.append("CORS配置过于宽松，生产环境建议限制具体域名")
    
    def _validate_wechat_config(self):
        """验证微信配置"""
        wechat_keys = ['WECHAT_APPID', 'WECHAT_SECRET']
        
        for key in wechat_keys:
            if not self.config.get(key):
                self.warnings.append(f"缺少微信配置项: {key}")
        
        # 检查微信支付配置
        pay_keys = ['WECHAT_APP_ID', 'WECHAT_MCH_ID', 'WECHAT_PAY_KEY']
        pay_config_count = sum(1 for key in pay_keys if self.config.get(key))
        
        if pay_config_count > 0 and pay_config_count < len(pay_keys):
            self.warnings.append("微信支付配置不完整，部分功能可能无法使用")
    
    def _validate_upload_config(self):
        """验证文件上传配置"""
        upload_folder = self.config.get('UPLOAD_FOLDER', '')
        if not upload_folder:
            self.errors.append("缺少UPLOAD_FOLDER配置")
        elif not os.path.exists(upload_folder):
            self.warnings.append(f"上传目录不存在: {upload_folder}")
        
        max_size = self.config.get('MAX_CONTENT_LENGTH', 0)
        if max_size > 50 * 1024 * 1024:  # 50MB
            self.warnings.append("文件上传大小限制过大，可能影响服务器性能")
    
    def _validate_logging_config(self):
        """验证日志配置"""
        log_file = self.config.get('LOG_FILE', '')
        if log_file:
            log_dir = os.path.dirname(log_file)
            if not os.path.exists(log_dir):
                self.warnings.append(f"日志目录不存在: {log_dir}")
        
        log_level = self.config.get('LOG_LEVEL', 'INFO')
        valid_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
        if log_level not in valid_levels:
            self.errors.append(f"无效的日志级别: {log_level}")


def validate_config(config_dict: Dict) -> Tuple[bool, List[str], List[str]]:
    """验证配置的便捷函数"""
    validator = ConfigValidator(config_dict)
    return validator.validate_all()


def print_validation_results(is_valid: bool, errors: List[str], warnings: List[str]):
    """打印验证结果"""
    print("🔍 配置验证结果:")
    print("=" * 50)
    
    if is_valid:
        print("✅ 配置验证通过")
    else:
        print("❌ 配置验证失败")
    
    if errors:
        print("\n❌ 错误:")
        for error in errors:
            print(f"  - {error}")
    
    if warnings:
        print("\n⚠️ 警告:")
        for warning in warnings:
            print(f"  - {warning}")
    
    print("=" * 50)


if __name__ == '__main__':
    # 测试配置验证
    test_config = {
        'SECRET_KEY': 'dev-secret-key-change-in-production',
        'FLASK_ENV': 'development',
        'MYSQL_HOST': 'localhost',
        'MYSQL_PORT': 3306,
        'MYSQL_USER': 'root',
        'MYSQL_PASSWORD': '',
        'MYSQL_DATABASE': 'venue_booking',
        'JWT_SECRET_KEY': 'jwt-secret-key-change-in-production',
        'CORS_ORIGINS': '*',
        'UPLOAD_FOLDER': 'uploads',
        'LOG_LEVEL': 'INFO'
    }
    
    is_valid, errors, warnings = validate_config(test_config)
    print_validation_results(is_valid, errors, warnings) 